package com.qdxwx.web.controller.user;

import com.qdxwx.common.cache.CacheUtils;
import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKRequest;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.data.service.user.UserThirdService;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserThird;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class MobileBindController extends BaseController {

    @Autowired
    private UserThirdService userThirdService;
    @Autowired
    private UserService userService;

    //用户邦定手机页
    @RequestMapping("/binding/mobile.html")
    public String binding(HttpServletRequest request) {
        long userId = LoginUser.getUserId(request);
        if(userId < 1){
            return "redirect:/auth/login.html";
        }
        if (TKRequest.isMobileBrowse(request)){
            return getViewPathH5("auth/binding-mobile");
        }
        return getViewPath("auth/binding-mobile");
    }

    @RequestMapping("/binding/mobile.json")
    @ResponseBody
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult bindingMobile(HttpServletRequest request) throws RuntimeException {
        User loginUser = LoginUser.getUser(request);
        if(loginUser == null){
            return AjaxResult.error("登录超时！");
        }
        if(TKString.isNotEmpty(loginUser.getMobile())){
            return AjaxResult.error("已经绑定过手机啦！");
        }
        String mobile = TKString.trim(request.getParameter("mobile"));
        if (TKString.isEmpty(mobile)) {
            return AjaxResult.error("手机号码不能为空！");
        }
        if (!TKString.isMobile(mobile)) {
            return AjaxResult.error("手机号码格式错误！");
        }
        //从缓存提取手机验证码
        String mobileCodeNum = (String) CacheUtils.get(CacheConstants.MOBILE_SMS_PRE + mobile);
        //获得输入的手机验证码
        String mobileCode = TKString.trim(request.getParameter("mobileCode"));
        if (mobileCode.length() < 5 || !mobileCode.equals(mobileCodeNum)) {
            return AjaxResult.error("请输入正确的手机验证码！");
        }
        CacheUtils.remove(CacheConstants.MOBILE_SMS_PRE + mobile);

        UserThird userThird = userThirdService.getWx(loginUser.getUserId());
        if (userThird == null) {
            return AjaxResult.error("参数丢失，请重新发起绑定！");
        }
        User user = userService.getByMobile(mobile);

        int count;
        if (user == null) {
            user = userService.get(userThird.getUserId());
            user.setMobile(mobile);
            count = userService.updateMobile(user);
        }else {
            if(user.getIsAvailable() == 2){
                return AjaxResult.error("该手机号码被禁用！");
            }
            if(userThirdService.getWx(user.getUserId()) != null){
                return AjaxResult.error("该手机号码已被其他账户绑定！");
            }
            try {
                userService.combine(userThird.getUserId(), user);
                user = userService.get(loginUser.getUserId());
                user.setMobile(mobile);
                count = userService.updateMobile(user);
            } catch (RuntimeException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        return count > 0 ?AjaxResult.success():AjaxResult.error();
    }

}
